package com.ytjj.quartz.service;

import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.quartz.dao.CircleDao;
import com.ytjj.quartz.dao.OrdersDao;
import com.ytjj.quartz.enums.UserBalanceSourceEnums;
import com.ytjj.quartz.model.CircleMainRoleInfoResponse;
import com.ytjj.quartz.model.CircleOrdersInfoResponse;
import com.ytjj.quartz.model.OrderResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CircleService {
    @Resource
    private CircleDao circleDao;
    @Resource
    private OrdersDao ordersDao;
    @Autowired
    private UsersClient usersClient;

    /**
     * 团小圈活动下线
     * 根据结束时间来判断是否下线
     */
    public void circleActivityOffLine() {
        circleDao.circleActivityOffLine();
    }

    public void updateCircleActivityOffLineByProductStatus() {
        List<Integer> circleIds = circleDao.selectCircleIds();
        if (CollectionUtils.isEmpty(circleIds)) {
            return;
        }
        circleDao.updateCircleActivityOffLineByProductStatus(circleIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public void calculationCircleOrderIncome() {
        //1.佣金未结算订单集合
        List<CircleOrdersInfoResponse> ordersInfoResponseList = circleDao.selectPayOrders();
        //2.订单已签收并且未结算订单
        List<CircleOrdersInfoResponse> ordersStatus3List = ordersInfoResponseList.stream()
                .filter(s -> s.getOrderStatus().equals("3")).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(ordersStatus3List)) {
            //结算佣金
            ordersStatus3List.stream().forEach(item -> {
                //获取佣金金额
                doHandle(item, 3);
            });
        }
        //3.订单未签收并且未结算订单
        List<CircleOrdersInfoResponse> ordersStatusNoEqual3List = ordersInfoResponseList.stream()
                .filter(s -> !s.getOrderStatus().equals(3)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(ordersStatusNoEqual3List)) {
            List<Integer> orderIdList = ordersStatusNoEqual3List.stream().map(CircleOrdersInfoResponse::getOrderId).collect(Collectors.toList());
            if(orderIdList.isEmpty()){
                return;
            }
            //查询15天以前创建的订单
            List<OrderResp> halfMonthOrderIds = ordersDao.selectOrderCreateTimeHalfMonthBefore(orderIdList);
            if (CollectionUtils.isEmpty(halfMonthOrderIds)) {
                return;
            }
            ordersStatusNoEqual3List.stream().forEach(item -> {
                halfMonthOrderIds.stream().forEach(s -> {
                    if (item.getOrderId().equals(s.getOrderId())) {
                        //获取佣金金额
                        doHandle(item, 1);
                    }
                });
            });
        }
    }

    private void doHandle(CircleOrdersInfoResponse item, Integer status) {
        //获取佣金金额
        if (3 == status) {
            LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
            ldt = ldt.plusDays(-7);
            //7天前的时间戳
            long sevenDayBefore = ldt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            // 签收标志 true-已达到签收7天时间 false-未达到签收7天时间
            AtomicBoolean checkFlag = new AtomicBoolean(false);
            List<Date> receiveDates = ordersDao.getOrderReceiveTime(item.getOrderId());
            receiveDates.stream().forEach(s -> {
                if (s.getTime() <= sevenDayBefore) {
                    checkFlag.set(true);
                }
            });
            //如果签收时间不满足7天前，则直接返回
            if (!checkFlag.get()) {
                return;
            }
        }else if (1 == status) {
            LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
            ldt = ldt.plusDays(-15);
            //15天前的时间戳
            long sevenDayBefore = ldt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            AtomicBoolean checkFlag = new AtomicBoolean(false);
            //改成了取订单创建时间，因为发货时间没有维护起来
            List<Date> receiveDates = ordersDao.getOrderDeliveryTime(item.getOrderId());
            receiveDates.stream().forEach(s -> {
                if (s.getTime() <= sevenDayBefore) {
                    checkFlag.set(true);
                }
            });
            //如果发货时间不满足15天前，则直接返回
            if (!checkFlag.get()) {
                return;
            }
        }

        log.info("===结算佣金开始==={}, {}, {}", item.getId(), item.getHeadId(), item.getBrokerage());
        grantBrokerage(item.getHeadId(), null == item.getBrokerage() ? BigDecimal.ZERO : item.getBrokerage());
        //更新佣金结算标志=1
        log.info("===更新佣金结算标志id={}",item.getId());
        circleDao.updateBrokerageGrantFlag(item.getId());
    }

    /**
     * 发放佣金
     * @param headId 团长id
     * @param brokerage 佣金金额
     */
    private void grantBrokerage(Integer headId, BigDecimal brokerage) {
        List<CircleMainRoleInfoResponse> mainRoles = circleDao.selectCircleMainRoleByHeadId(headId);
        if (CollectionUtils.isEmpty(mainRoles)) {
            return;
        }
        Integer userId = mainRoles.get(0).getUserId();
        usersClient.addBalance(brokerage, userId, UserBalanceSourceEnums.CIRCLE_BUY.name());
    }
}
